package com.adinnet.core.weiMsg;

import com.adinnet.common.utils.PropertiesConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.Key;


/**
 * @author sunjianbo
 * @date 2019/1/26 0026 10:37
 */
public class WXUtils {
    private static final Logger log = LoggerFactory.getLogger(WXUtils.class);

    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;

    public static void main(String[] args) {

        String result = decryptData(
                "ItRDv9rcgpuZ+nwMMRZxn+3hCztgrBjk4ato5A4yQmLrewICOCwGwNkGt9kMWk+nQIeGlwDZD60XCCFe46CFFM5mfv7cssUxmO3Pyg2pMmexF4aRkfP3BWORbsa+GSIDLnRdLfBbhKCPgmYXvA4b5EI+hvs1inAJvm/rGZDIxjMeB5BJMz37L/HAGkChRjcVE7U91TPeQfayjcsXhN1aBQ==",
                "5IEHX2GzsRoinNbobqjGwQ==",
                "R0T8y5IS47zgi+LqV2j6Jg=="
        );
        System.out.println("result = " + result);
        JSONObject json = JSONObject.parseObject(result);
        System.out.println(json.get("purePhoneNumber"));

    }

    public static String decryptData(String encryptDataB64, String sessionKeyB64, String ivB64) {
        return new String(
                decryptOfDiyIV(
                        Base64.decode(encryptDataB64),
                        Base64.decode(sessionKeyB64),
                        Base64.decode(ivB64)
                )
        );
    }

        /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @param ivs           自定义对称解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    private static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        byte[] encryptedText = null;
        init(keyBytes);
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static void init(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);

        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(ALGORITHM_STR,"BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, KEY_ALGORITHM );
            AlgorithmParameters parameters = AlgorithmParameters.getInstance(KEY_ALGORITHM);
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                log.info("从微信获取的用户信息\t"+result);
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 带参数无限个数小程序码接口
     * API https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html#method-cloud
    * @param access_token
    * @param path
    * @param width
    * @return
    */
    public static InputStream getwxacodeunlimit(String page,String scene,String width){
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + WX_TokenUtil.getWXToken().getAccess_token();
        scene = scene == null ? "" : scene;
        width = width == null ? "280" : width;
        // 接收参数json列表
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("scene", scene);
        jsonParam.put("page", page);
        jsonParam.put("width", Integer.parseInt(width));
        jsonParam.put("auto_color", false);
        Map<String,Object> line_color = new HashMap<>();
        line_color.put("r", 0);
        line_color.put("g", 0);
        line_color.put("b", 0);
        jsonParam.put("line_color", line_color);
        InputStream instreams = WX_HttpsUtil.doWXPost(url,jsonParam);
        if(instreams==null) log.error("出错获取二维码失败！");
        return instreams;
    }    

    /**
     * 根据url读取文件
     * @param mediaUrl
     * @return
     * @throws IOException
     */
    public static byte[] readUrlBytes(String mediaUrl) throws IOException {
        URL url = new URL(mediaUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.connect();
        InputStream cin = httpConn.getInputStream();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = cin.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        cin.close();
        byte[] fileData = outStream.toByteArray();
        outStream.close();
        return fileData;
    }
    /**
     * API https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     * 获取登录凭证
     * @param jsCode  从前端 wx.login() 中获取
     * @return  openid , session_key
     */
    public static JsCodeForm jscode2session(String jsCode){
        String url =  PropertiesConfig.getOpenIdUrl
            +"?appid="+PropertiesConfig.weiXinSmallProgramId
            +"&secret="+PropertiesConfig.weiXinSmallSecret
            +"&js_code="+jsCode+"&grant_type=authorization_code";
        JSONObject result = WX_HttpsUtil.httpsRequest(url, "GET",null );
        String body = JSON.toJSONString(result);
        return JSON.parseObject( body , JsCodeForm.class);
    } 
}
